package com.nuc.kl.base;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import org.apache.struts2.ServletActionContext;

import com.nuc.kl.module.basedata.service.DirectionSerivce;
import com.nuc.kl.module.basedata.service.NavigationSerivce;
import com.nuc.kl.module.basedata.service.ReferenceTypeSerivce;
import com.nuc.kl.module.example.entity.Example;
import com.nuc.kl.module.example.service.ExampleSerivce;
import com.nuc.kl.module.kpoint.service.KPointService;
import com.nuc.kl.module.kpoint.service.KnowledgeCheckService;
import com.nuc.kl.module.kpoint.service.KnowledgeLogService;
import com.nuc.kl.module.kpoint.service.ReferenceService;
import com.nuc.kl.module.usermanager.entity.People;
import com.nuc.kl.module.usermanager.entity.User;
import com.nuc.kl.module.usermanager.service.PrivilegeService;
import com.nuc.kl.module.usermanager.service.RoleService;
import com.nuc.kl.module.usermanager.service.StudentService;
import com.nuc.kl.module.usermanager.service.TeacherService;
import com.nuc.kl.module.usermanager.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
//哈哈哈哈哈哈哈曹宁第一次修改
@SuppressWarnings( { "unchecked", "serial" })
public abstract class BaseAction<T> extends ActionSupport implements
		ModelDriven<T> {

	// =======================ModelDriven的支持==========================

	protected T model;
	protected List<T> models;
	protected HttpServletResponse response = ServletActionContext.getResponse();
	protected HttpServletRequest request = ServletActionContext.getRequest();

	public BaseAction() {
		try {
			// 通过反射获取model的真是类型
			ParameterizedType pt = (ParameterizedType) this.getClass()
					.getGenericSuperclass();
			Class<T> clazz = (Class<T>) pt.getActualTypeArguments()[0];
			// 通过反射创建model的实例
			model = clazz.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	public T getModel() {
		return model;
	}

	/**
	 * 转化为json对象
	 */
	public void toBeJson(List list, long total, final String[] filterStr)
			throws Exception {

		JsonConfig config = new JsonConfig();
		config.setJsonPropertyFilter(new PropertyFilter() {
			public boolean apply(Object source, String name, Object value) {
				for (int i = 0; i < filterStr.length; i++) {
					if (name.contains(filterStr[i])) {
						return true;
					}
				}
				return false;
			}
		});

           
         JSONObject jobj = new JSONObject();//new一个JSON  
         jobj.accumulate("total",total );//total代表一共有多少数据  
         jobj.accumulate("rows", list,config);//row是代表显示的页的数据  
         response.setCharacterEncoding("utf-8");//指定为utf-8  
         response.getWriter().write(jobj.toString());//转化为JSOn格式  
           
    }
	 
	 
	 /**
	  * 改良
	 * @param list
	 * @param total
	 * @param filterStr
	 * @throws Exception
	 */
	public void toBeJsonArray(List list,final String[] filterStr) throws Exception{  
         
         JsonConfig config = new JsonConfig();
         config.setJsonPropertyFilter(new PropertyFilter() {
			public boolean apply(Object source, String name, Object value) {
				for (int i = 0; i < filterStr.length; i++) {
					if(name.equals(filterStr[i])){
						return true;
					}
				}
				return false;
			}
		});
         
       response.setCharacterEncoding("utf-8");//指定为utf-8  
       response.getWriter().write(JSONArray.fromObject(list,config).toString());//转化为JSOn格式  
         
  }  
	 
	 
	 private Long findId ;
	 
	 public String getById() throws Exception{
		 
		 Class modelClazz = getModel().getClass();//获取当前对象类
		 String className = modelClazz.getSimpleName();//获取当前对象类的简单名称
		 
		 StringBuffer sb = new StringBuffer(className);//将首字母小写
		 sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
		 
		 String classServiceName = className + "Service"; 
		 
		 Class cl = Class.forName(classServiceName);
		 Method getById =  cl.getMethod("getById", Long.class);//根据方法名，参数类型获得方法 
		 Method getcount =  cl.getMethod("count", modelClazz);//根据方法名，参数类型获得方法 
		 
		 List list =   (List) getById.invoke(cl, findId);
		 Long count =   (Long) getcount.invoke(cl, model);
		 
		 String[] strs = {"parent","children"};
		 
		 toBeJson(list, count,strs);
		 
		 return null;
	 }

	public Long getFindId() {
		return findId;
	}

	public void setFindId(Long findId) {
		this.findId = findId;
	}


	/**
	 * 转化为json对象
	 */
	public void listToJson(List list, final String[] filterStr)
			throws Exception {

		JsonConfig config = new JsonConfig();
		config.setJsonPropertyFilter(new PropertyFilter() {
			public boolean apply(Object source, String name, Object value) {
				for (int i = 0; i < filterStr.length; i++) {
					if (name.equals(filterStr[i])) {
						return true;
					}
				}
				return false;
			}
		});

		JSONArray jsonArray = new JSONArray();

		response.setCharacterEncoding("utf-8");// 指定为utf-8
		System.out.println("--------");
		System.out.println(jsonArray.fromObject(list,config).toString());
		System.out.println("-----------");
		response.getWriter().write(jsonArray.fromObject(list,config).toString());// 转化为JSOn格式

	}

	/**
	 * 获取当前登录的用户
	 * 
	 * @return
	 */
	protected People getCurrentUser() {

		return (People)ActionContext.getContext().getSession().get("people");
	}

	public void sendMessage(String status,String msg) throws IOException{
	//输出提示语句
		String str = "{\"status\":\""+status+"\" , \"message\":\""+msg+"!\"}";
		response.setCharacterEncoding("utf-8");//指定为utf-8  
		response.getWriter().write(str);
	}
	// =======================Service实例的声明==========================

	@Resource
	protected ExampleSerivce exampleService;

	// kpoint模块
	@Resource
	protected ReferenceService referenceService;
	@Resource
	protected KPointService kPointService;
	@Resource
	protected KnowledgeCheckService knowledgeCheckService;
	@Resource
	protected KnowledgeLogService knowledgeLogService;

	// basedata模块
	@Resource
	protected DirectionSerivce directionService;
	@Resource
	protected ReferenceTypeSerivce referenceTypeService;
	@Resource
	protected NavigationSerivce navigationService;

	// usermanager模块
	@Resource
	protected RoleService roleService;
	@Resource
	protected UserService userService;
	@Resource
	protected PrivilegeService privilegeService;
	@Resource
	protected StudentService studentService;
	@Resource
	protected TeacherService teacherService;
}
